//
//  BookArchiveView.swift
//  KoiAccounting
//
//  Created by 纪洪文 on 04.04.25.
//

import SwiftUI

struct BookArchiveView: View {
    
    @Environment(\.presentToast) var presentToast
    
    @State private var showActionSheet = false
    
    @State private var selectedBook: AccountingBook?
    
    @StateObject var viewModel = BookArchiveViewModel()
    
    var body: some View {
        List {
            ForEach(viewModel.archiveBooks.indices, id:\.self) { index in
                let book = viewModel.archiveBooks[index]
                BookItemView(book: book, viewType: .more, onMoreClick: {
                    selectedBook = book
                    showActionSheet = true
                })
                .koiListRowClear()
                .koiItemRowStyle()
            }
        }
        .listStyle(.plain)
        .listRowBackground(Color.clear)
        .background(Color.koiColorBackground)
        .padding(EdgeInsets(top: 0, leading: 20, bottom: 0, trailing:20)) // 去除边距
        .ignoresSafeArea(.container, edges: .bottom)
        .onAppear {
            viewModel.loadArchiveBooks()
        }
        .actionSheet(isPresented: $showActionSheet) {
            ActionSheet(title: Text(""), buttons: [
                .default(Text("取消归档")) {
                    viewModel.unArchive(book: selectedBook)
                },
                .default(Text("删除")) {
                    
                }
            ])
        }
        .onChange(of: viewModel.unArchiveState) { newValue in
            if (newValue == "success") {
                viewModel.unArchiveState = ""
                presentToast(.init(message: "已取消归档"))
                viewModel.loadArchiveBooks()
            }
        }
        .koiToolbar(title: Text("归档账本"))
        .background(Color.koiColorBackground)
    }
}

#Preview {
    BookArchiveView()
}
